<?php

namespace app\api\controller\system;
use app\api\service\log\AdminOperateLogService;
use app\api\service\system\MenuService;
use app\api\service\system\RoleService;
use app\BaseController;
use app\api\service\system\RoleMenuService;
use app\util\AdminUserUtil;
use app\util\CommonUtil;
use app\api\service\develop\DatagridColumnService;
use app\util\ResponseUtil;

class RoleMenu extends BaseController
{
    public function getRoleMenuInfo()
    {
        $id = $this->requestData['id'];
        $service = new RoleMenuService();
        $finalData = $service->getRoleMenuInfoById($id);
        return ResponseUtil::success($finalData);
    }

    public function getRoleMenuList()
    {
        $pageIndex = $this->requestData['page'];
        $pageSize = $this->requestData['rows'];
        $service = new RoleMenuService();
        $list = $service->getRoleMenuList($this->requestData, $pageIndex, $pageSize);
        $total = $service->getRoleMenuTotalNum($this->requestData);
        $finalData = CommonUtil::getPaginationData($list, $total);
        return ResponseUtil::success($finalData);
    }

    public function getRoleMenuOption()
    {
        $service = new RoleMenuService();
        $list = $service->getRoleMenuOption($this->requestData);
        return ResponseUtil::success($list);
    }

    public function checkRoleMenu()
    {
        $operationText = "绑定";
        try{
            $aField = 'role_id';
            $bField = 'menu_id';
            if(empty($this->requestData[$aField]) || empty($this->requestData[$bField])){
                return ResponseUtil::failure("请选择角色和菜单");
            }

            $roleId     = $this->requestData[$aField];
            $menuId     = $this->requestData[$bField];
            $serviceRole = new RoleService();
            $roleInfo = $serviceRole->getRoleInfoById($roleId);
            if(!$roleInfo){
                return ResponseUtil::failure("角色不存在");
            }

            $serviceMenu = new MenuService();
            $menuInfo = $serviceMenu->getMenuInfoById($menuId);
            if(!$menuInfo){
                return ResponseUtil::failure("菜单不存在");
            }

            //勾选某个菜单，则其父菜单和子菜单都要勾选上
            $serviceRoleMenu = new RoleMenuService();
            $arrParentMenuId = $serviceMenu->getAllParentMenuId($menuId);
            $arrChildMenuId = $serviceMenu->getAllChildrenMenuId($menuId);
            $allMenuId = array_merge($arrChildMenuId, $arrParentMenuId, [$menuId]);

            $arrUpdateRoleMenuId = array();
            foreach($allMenuId as $singleMenuId){
                $condition = array(
                    $aField    => $roleId,
                    $bField    => $singleMenuId
                );
                $dataExist = $serviceRoleMenu->getRoleMenuInfoByCondition($condition);
                if(!$dataExist){
                    //插入
                    $addData = array_merge($condition, array('status' => 1));
                    $serviceRoleMenu->addRoleMenu($addData);
                }else{
                    //更新
                    $arrUpdateRoleMenuId[] = $dataExist['id'];
                }
            }
            if($arrUpdateRoleMenuId){
                $serviceRoleMenu->editRoleMenuByManyId($arrUpdateRoleMenuId, array('status' => 0));
            }



            if($infoData){
                if(1 == $infoData['status']){
                    if(1 == $roleId){
                        return ResponseUtil::failure("系统管理员角色不可取消");
                    }
                    $operationText = "解绑";
                    $dataUpdate['status'] = 0;
                    $arrChildMenuId = $serviceMenu->getAllChildrenMenuId($this->requestData[$bField]);
                    $allId = array_merge($arrChildMenuId, [$this->requestData[$bField]]);
                }else{
                    $dataUpdate['status'] = 1;
                    $arrParentMenuId = $serviceMenu->getAllParentMenuId($this->requestData[$bField]);
                    $arrChildMenuId = $serviceMenu->getAllChildrenMenuId($this->requestData[$bField]);
                    $allId = array_merge($arrChildMenuId, $arrParentMenuId, [$this->requestData[$bField]]);
                }
                $condition = array(
                    $aField    => $roleId,
                    $bField    => $allId
                );
                $res = $service->updateRow($condition, $dataUpdate);
            }else{
                //此处一定是新增
                $arrParentMenuId = $serviceMenu->getAllParentMenuId($this->requestData[$bField]);
                $arrChildMenuId = $serviceMenu->getAllChildrenMenuId($this->requestData[$bField]);
                $allId = array_merge($arrChildMenuId, $arrParentMenuId, [$this->requestData[$bField]]);
                $addData = [];
                foreach($allId as $id){
                    $addData[] = [$aField    => $roleId, $bField => $id];
                }
                $res = $service->createMultiRow($addData);
            }
            if($res){
                $messageCn = '角色'.$operationText."菜单：[<b>角色名称</b>]".$roleInfo['role_name'].", [<b>菜单名称</b>]".$menuInfo['menu_name_cn'];
                $messageEn = '';
                $logData = [
                    'subject_id' => $roleInfo['id'],
                    'remark'  => '',
                    'description_en' => $messageEn,
                    'description_cn' => $messageCn,
                ];
                UserUtil::addOperateLog('Role', OperateLogService::ARR_ACTION_TYPE['edit'], $logData);
                return ResponseUtil::success($res, $operationText."成功");
            }else{
                return ResponseUtil::failure($operationText."失败");
            }
        }catch(\Exception $e){
            $errorMessage = $e->getMessage()."(Line:".$e->getLine()." in ".$e->getFile().")";
            CommonUtil::addErrorLog('RoleMenu', 'toggleRoleMenu', $errorMessage);
            return ResponseUtil::failure("编辑失败");
        }
    }

    public function uncheckRoleMenu()
    {
        $operationText = "解绑";
        try{
            $aField = 'role_id';
            $bField = 'menu_id';
            if(empty($this->requestData[$aField]) || empty($this->requestData[$bField])){
                return ResponseUtil::failure("请选择角色和菜单");
            }

            $roleId     = $this->requestData[$aField];
            $menuId     = $this->requestData[$bField];
            $serviceRole = new RoleService();
            $roleInfo = $serviceRole->getRoleInfoById($roleId);
            if(!$roleInfo){
                return ResponseUtil::failure("角色不存在");
            }

            $serviceMenu = new MenuService();
            $menuInfo = $serviceMenu->getMenuInfoById($menuId);
            if(!$menuInfo){
                return ResponseUtil::failure("菜单不存在");
            }

            if(1 == $roleInfo['is_super']){
                return ResponseUtil::failure("超级管理员角色的菜单权限不可取消");
            }

            $serviceRoleMenu = new RoleMenuService();
            $condition = array(
                $aField    => $roleId,
                $bField    => $menuId
            );
            $infoData = $serviceRoleMenu->getRoleMenuInfoByCondition($condition);
            if(!$infoData){
                return ResponseUtil::failure("数据有误");
            }

            $arrChildMenuId = $serviceMenu->getAllChildrenMenuId($this->requestData[$bField]);
            $allId = array_merge($arrChildMenuId, [$this->requestData[$bField]]);

            $condition = array(
                $aField    => $roleId,
                $bField    => $allId
            );
            $res = $serviceRoleMenu->editRoleMenuByCondition($condition, array('status' => 0));
            if($res){
                $message = '角色'.$operationText."菜单：[<b>角色名称</b>]".$roleInfo['role_name'].", [<b>菜单名称</b>]".$menuInfo['menu_name_cn'];
                $logData = [
                    'subject_id' => $roleInfo['id'],
                    'remark'  => '',
                    'description' => $message,
                ];
                AdminUserUtil::addOperateLog('Role', AdminOperateLogService::ARR_ACTION_TYPE['edit'], $logData);
                return ResponseUtil::success($res, $operationText."成功");
            }else{
                return ResponseUtil::failure($operationText."失败");
            }
        }catch(\Exception $e){
            CommonUtil::addErrorLog(__CLASS__, __FUNCTION__,  CommonUtil::getExceptionMessage($e));
            return ResponseUtil::failure($operationText."失败");
        }
    }

    public function createRoleMenu()
    {
        try{
            if(empty($this->requestData['page_code'])){
                return ResponseUtil::failure("页面标识码不可为空");
            }
            $pageCode = $this->requestData['page_code'];

            $serviceDatagridColumn = new DatagridColumnService();
            $columnList = $serviceDatagridColumn->getDatagridColumnOption(['page_code' => $pageCode, 'is_in_add'=>1, 'is_require' => 1]);
            foreach($columnList as $columnItem){
                if(empty($this->requestData[$columnItem['column_name']])){
                    return ResponseUtil::failure($columnItem['column_title']."不可为空");
                }
            }
            $service = new RoleMenuService();
            $res = $service->addRoleMenu($this->requestData);
            if($res){
                $addInfo = CommonUtil::getDataInsertMessage($res, ['##field_1##' => '##field_text_1##', '##field_2##'=>'##field_text_2##']);
                $messageCn = '新增任务项,'.$addInfo;
                $messageEn = '';
                $logData = [
                    'subject_id' => $res['new_id'],
                    'remark'  => $res['task_item_no'],
                    'description_en' => $messageEn,
                    'description_cn' => $messageCn,

                ];
                AdminUserUtil::addOperateLog('RoleMenu', AdminOperateLogService::ARR_ACTION_TYPE['add'], $logData);
                return ResponseUtil::success($res);
            }else{
                return ResponseUtil::failure("新增失败");
            }
        }catch(\Exception $e){
            CommonUtil::addErrorLog(__CLASS__, __FUNCTION__,  CommonUtil::getExceptionMessage($e));
            return ResponseUtil::failure("新增失败");
        }
    }

    public function modifyRoleMenu()
    {
        try{
            if(empty($this->requestData['id'])){
                return ResponseUtil::failure("请指定要编辑的任务");
            }
            if(empty($this->requestData['##field_1##'])){
                return ResponseUtil::failure("请填写##field_text_1##");
            }
            if(empty($this->requestData['##field_2##'])){
                return ResponseUtil::failure("请填写##field_text_2##");
            }
            $id = $this->requestData['id'];
            $service = new RoleMenuService();
            $oldInfo = $service->getRoleMenuInfoById($id);
            if(empty($oldInfo)){
                return ResponseUtil::failure("任务不存在");
            }
            $res = $service->editRoleMenuById($id, $this->requestData);
            if($res){
                $changeInfo = CommonUtil::getChangeData($oldInfo, $this->requestData,['##field_1##' => '##field_text_1##', '##field_2##'=>'##field_text_2##', 'status'=>'状态']);
                $messageCn = '编辑任务项,'.$changeInfo['update_info'];
                $messageEn = '';
                $logData = [
                    'subject_id' => $id,
                    'remark'  => $oldInfo['##field_1##'],
                    'description_en' => $messageEn,
                    'description_cn' => $messageCn,
                ];
                UserUtil::addOperateLog('RoleMenu', UserOperateLogService::ARR_ACTION_TYPE['edit'], $logData);
                return ResponseUtil::success();
            }else{
                return ResponseUtil::failure("编辑失败");
            }
        }catch(\Exception $e){
            CommonUtil::addErrorLog(__CLASS__, __FUNCTION__,  CommonUtil::getExceptionMessage($e));
            return ResponseUtil::failure("编辑失败");
        }
    }

    public function trashRoleMenu()
    {
        try{
            $id = $this->requestData['id'];
            $service = new RoleMenuService();
            $info = $service->getRoleMenuInfoById($id);
            if(!$info){
                return ResponseUtil::failure("数据不存在");
            }
            $res = $service->deleteRoleMenuById($id);
            if($res){
                return ResponseUtil::success();
            }else{
                return ResponseUtil::failure("删除失败");
            }
        }catch(\Exception $e){
            CommonUtil::addErrorLog(__CLASS__, __FUNCTION__,  CommonUtil::getExceptionMessage($e));
            return ResponseUtil::failure("删除失败");
        }
    }

    public function deleteMultiRoleMenu(){
        try{
            $id = $this->requestData['id'];
            if(!is_array($id)){
                return ResponseUtil::failure("参数格式有误");
            }
            $service = new RoleMenuService();
            $deleteData = [];
            foreach($id as $value){
                $info = $service->getRoleMenuInfoById($value);
                if(!$info){
                    return ResponseUtil::failure("数据不存在");
                }
                $deleteData[] = $info;
            }
            $res = $service->deleteRoleMenuByManyId($id);
            if($res){
                $deleteInfo = CommonUtil::getDataDeleteMessage($deleteData, ['##field_1##', '##field_2##']);
                $messageCn = '删除任务项,'.$deleteInfo;
                $messageEn = '';
                $logData = [
                    'subject_id' => json_encode($id),
                    'remark'  => implode(',', array_column($deleteData, '##field_1##')),
                    'description_en' => $messageEn,
                    'description_cn' => $messageCn,
                ];
                UserUtil::addOperateLog('RoleMenu', UserOperateLogService::ARR_ACTION_TYPE['delete'], $logData);
                return ResponseUtil::success();
            }else{
                return ResponseUtil::failure("删除失败");
            }
        }catch(\Exception $e){
            CommonUtil::addErrorLog(__CLASS__, __FUNCTION__,  CommonUtil::getExceptionMessage($e));
            return ResponseUtil::failure("删除失败");
        }
    }

    public function toggleRoleMenu()
    {
        try{
            if(empty($this->requestData['id'])){
                return ResponseUtil::failure("请指定要编辑的数据");
            }

            $arrField = ['is_in_add', 'is_in_edit', 'is_require', 'is_hide', 'status'];
            $arrFieldTitle = ['is_in_add' => '新增是否包含', 'is_in_edit'=>'编辑是否包含', 'is_hide'=>'是否隐藏', 'status'=>'状态'];
            if(empty($this->requestData['field_name'])){
                return ResponseUtil::failure("请指定要编辑的列");
            }

            $id = $this->requestData['id'];
            $fieldName = $this->requestData['field_name'];
            if(!in_array($fieldName, $arrField)){
                return ResponseUtil::failure("不支持编辑当前列");
            }

            $service = new RoleMenuService();
            $oldInfo = $service->getRoleMenuInfoById($id);

            $updateData[$fieldName] = empty($this->requestData['value']) ? 2:$this->requestData['value'];
            $res = $service->editRoleMenuById($id, $updateData);
            if($res){
                $changeInfo = CommonUtil::getChangeData($oldInfo, $updateData,$arrFieldTitle);
                $messageCn = '编辑页面纵列,'.$changeInfo['update_info'];
                $messageEn = '';
                $logData = [
                    'subject_id' => $id,
                    'remark'  => $oldInfo['column_name'],
                    'description_en' => $messageEn,
                    'description_cn' => $messageCn,
                ];
                UserUtil::addOperateLog('RoleMenu', UserOperateLogService::ARR_ACTION_TYPE['edit'], $logData);
                return ResponseUtil::success();
            }else{
                return ResponseUtil::failure("更新失败");
            }
        }catch(\Exception $e){
            CommonUtil::addErrorLog(__CLASS__, __FUNCTION__,  CommonUtil::getExceptionMessage($e));
            return ResponseUtil::failure("更新失败");
        }
    }

    public function simpleUpdateRoleMenu()
    {
        try{
            if(empty($this->requestData['id'])){
                return ResponseUtil::failure("请指定要编辑的数据");
            }

            $id = $this->requestData['id'];
            $arrFieldTitle = ['sort' => '排序',  'status'=>'状态'];
            $service = new RoleMenuService();
            $oldInfo = $service->getRoleMenuInfoById($id);
            if(empty($oldInfo)){
                return ResponseUtil::failure("数据不存在");
            }
            $res = $service->editRoleMenuById($id, $this->requestData);
            if($res){
                $changeInfo = CommonUtil::getChangeData($oldInfo, $this->requestData, $arrFieldTitle);
                $messageCn = '编辑页面纵列,'.$changeInfo['update_info'];
                $messageEn = '';
                $logData = [
                    'subject_id' => $id,
                    'remark'  => $oldInfo['column_name'],
                    'description_en' => $messageEn,
                    'description_cn' => $messageCn,
                ];
                UserUtil::addOperateLog('RoleMenu', UserOperateLogService::ARR_ACTION_TYPE['edit'], $logData);
                return ResponseUtil::success();
            }else{
                return ResponseUtil::failure("编辑失败");
            }
        }catch(\Exception $e){
            CommonUtil::addErrorLog(__CLASS__, __FUNCTION__,  CommonUtil::getExceptionMessage($e));
            return ResponseUtil::failure("编辑失败");
        }
    }



}



